﻿using System.Collections.Generic;
using System.Data.SqlServerCe;
using System.IO;
using System.Reflection;
using MediaSage.Lib.Database.Entities.Client;
using MediaSage.Lib.UIFramework.Theme;
using MediaSage.Lib.Utilities;
using NHibernate;

namespace MediaSage.Lib.Client.Config
{
    public class Configuration
    {
        private string databaseLocation;
        public string BaseDirectory;
        public bool DefaultConfiguration;
        public ClientLogger Logger;
        public ClientConfigEntity configEntity;
        private ThemeManager themeManager;

        private readonly int popupLoggingLevel;

        public ThemeManager getThemeManager()
        {
            return themeManager;
        }

        public IList<ThemeEntity> Themes
        {
            get { return configEntity.Themes; }
            set { configEntity.Themes = value; }
        }

        public ThemeEntity ActiveTheme
        {
            get { return configEntity.ActiveTheme; }
            set { configEntity.ActiveTheme = value; }
        }

        public string ThemeDirectory
        {
            get { return configEntity.ThemeDirectory; }
        }

        public int LogLevel
        {
            get { return configEntity.LogLevel; }
            set { configEntity.LogLevel = value; }
        }

        public string LogFile
        {
            get { return configEntity.LogFile; }
            set { configEntity.LogFile = value; }
        }

        public int PopupLogLevel
        {
            get { return configEntity.PopupLogLevel; }
            set { configEntity.PopupLogLevel = value; }
        }

        public Configuration()
        {
            DefaultConfiguration = false;
#if DEBUG
            RegistryHelper.DeleteKey(@"SOFTWARE\MediaSage\DatabaseLocation");
#endif
            if (RegistryHelper.KeyExists(@"SOFTWARE\MediaSage\InstallRoot"))
            {
                BaseDirectory = (string)RegistryHelper.GetKeyValue(@"SOFTWARE\MediaSage\Client", "InstallRoot");
            }
            else
            {
                BaseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                RegistryHelper.WriteKey(@"SOFTWARE\MediaSage\Client\InstallRoot", BaseDirectory, true);
            }
            if (RegistryHelper.KeyExists(@"SOFTWARE\MediaSage\DatabaseLocation"))
            {
                databaseLocation = (string)RegistryHelper.GetKeyValue(@"SOFTWARE\MediaSage", "DatabaseLocation");
            }
            else
            {
                databaseLocation =
                    Path.Combine(
                        path1:
                            RegistryHelper.KeyExists(@"SOFTWARE\MediaSage\InstallRoot")
                                ? BaseDirectory
                                : Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                        path2: "MediaSage.sdf");
            }
            bool dbInit = false;
            if (!File.Exists(databaseLocation))
            {
                databaseLocation = Path.Combine(path1: Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                                path2: "MediaSage.sdf");
                RegistryHelper.WriteKey(@"SOFTWARE\MediaSage\DatabaseLocation", databaseLocation, true);
                if (!File.Exists(databaseLocation))
                {
                    var sqlCeEngine = new SqlCeEngine("Data Source=" + databaseLocation);
                    sqlCeEngine.CreateDatabase();
                    DBUtil.CreateTables(databaseLocation);
                    RegistryHelper.SetKeyValue(@"SOFTWARE\MediaSage", "DatabaseLocation", databaseLocation);
                    dbInit = true;
                }
            }
            if (!dbInit)
            {
                DBUtil.Init(databaseLocation);
            }

            configEntity =
                (ClientConfigEntity)DBUtil.GetSession().CreateCriteria(typeof(ClientConfigEntity)).UniqueResult();
            if (configEntity == null)
            {
                configEntity = new ClientConfigEntity();
                CreateDefaultConfig(DBUtil.GetSession());
                DefaultConfiguration = true;
                configEntity =
                    (ClientConfigEntity)DBUtil.GetSession().CreateCriteria(typeof(ClientConfigEntity)).UniqueResult();
            }

            // Now initialize the ActiveTheme
            themeManager = new ThemeManager(this);
        }

        /// <summary>
        /// Set the defaults
        /// </summary>
        /// <param name="session"></param>
        private void CreateDefaultConfig(ISession session)
        {
            if (!RegistryHelper.KeyExists(@"SOFTWARE\MediaSage\InstallRoot"))
            {
                RegistryHelper.SetKeyValue(@"SOFTWARE\MediaSage", "InstallRoot", BaseDirectory);
            }
            ITransaction transaction = session.BeginTransaction();

#if DEBUG
            this.LogLevel = 0;
            this.PopupLogLevel = 1;
#else
            this.PopupLogLevel = 2;
            this.LogLevel=2;
#endif
            this.LogFile = Path.Combine(BaseDirectory, "MediaSage.Client.Log");
            configEntity.Save();
        }

        public void Save()
        {
            configEntity.Save();
        }

        public void SaveOrUpdate()
        {
            configEntity.SaveOrUpdate();
        }
    }
}